package com.cx.algrithm.leetcode.day1;

/**
 * @Author: robert.song
 * @Date: Created in 2021/12/21
 */

/**
 * 搜索插入：
 * <p>
 * 首先搜索 有序数组 有无要插入数值，有返回其索引，无将自己待插入位置索引返回
 */
public class SearchInsert {
    public static void main(String[] args) {
        System.out.println(searchInsert(new int[]{1, 3, 5, 6, 8}, 7));
    }

    public static int searchInsert(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return left;
    }
}
